/*
 * Copyright 2008 Lamen Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
*/

package org.lamen.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Utilitarian class to help the file manipulation in test development.
 * 
 * @author danielfireman
 * 
 * @date Jan 12, 2009
 */
public class FileTestUtils {

  private static final String TMP_FILE_PREFIX = "lamen_aux";

  /**
   * Map to keep the temporary files. It is protected to ease tests.
   */
  protected Map<String, File> temporaryFiles;

  public FileTestUtils() {
    temporaryFiles = new HashMap<String, File>();
  }

  /**
   * This method cleans up all test. It means delete temporary files, free memory and etc
   */
  public void finalizeTest() {
    for (File file : temporaryFiles.values()) {
      file.delete(); // as this map has only files, the boolean return will not be used
    }
    temporaryFiles.clear();
  }

  /**
   * Create an temporary file and internally registers it to deletion when the {@link FileTestUtils#finalizeTest()} is
   * called.
   * 
   * @see FileTestUtils#finalizeTest()
   * 
   * @param fileContent Some content to fill the temporary file. Set this parameter to null to generate an empty file.
   * @return The name of the file.
   */
  public File createTempFile(String fileContent) throws IOException {
    File returnedFile = File.createTempFile(TMP_FILE_PREFIX, null);
    temporaryFiles.put(returnedFile.getAbsolutePath(), returnedFile);
    
    if (fileContent != null) {
      if (returnedFile.canWrite()){
        FileWriter writer = new FileWriter(returnedFile);
        writer.write(fileContent);
        writer.close();
      } else {
        throw new IOException("Can not write the temporary file " + returnedFile.getAbsolutePath());
      }
    } 
    
    return returnedFile;
  }

  /**
   * The invocation of this method behaves in exactly the same way as the invocation 
   * <code>createTempFile(null)</code>.
   * 
   * @see FileTestUtils#createTempFile(String)
   */
  public File createTempFile() throws IOException {
    return createTempFile(null);
  }
}
